//
//  NetWorkTools.swift
//  PhotoBrowser
//
//  Created by 游强辉 on 16/4/27.
//  Copyright © 2016年 youqianghui. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType {
    case GET
    case POST
}

class NetWorkTools: AFHTTPSessionManager {
    //1.设置单例
    static let shareNetWorkTools : NetWorkTools = {
        let tool = NetWorkTools()
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tool
    }()
    
}

//MARK:-封装网络请求

extension NetWorkTools {
    func request(requestType : RequestType, urlString : String, parameters : [String : AnyObject], finish : (result : AnyObject?, error : NSError?) -> ()) {
        
        //1.定义成功后的闭包
        let successCallBack = { (task : NSURLSessionDataTask, result : AnyObject?) -> Void in
            finish(result : result, error : nil)
            }
        
        //2.定义失败的闭包
        let failureCallBack = { (task : NSURLSessionDataTask?, error : NSError) -> Void in
            finish(result: nil, error: error)
        }
        
        //3.发送请求
        
        if requestType == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }else
        {
            POST(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
    }
}

//  MARK:-请求首页数据
extension NetWorkTools {
    func loadHomeData(offset : Int, finish : (result : [[String : AnyObject]]?, error : NSError?) -> ()) {
        //1.获取请求的URL
        let urlString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
        
        //2.获取参数
        let parameters = ["offset" : "\(offset)", "limit" : "30", "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"]
        
        //3.发送网络请求
        request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                finish(result: nil, error: error)
            }
            
            guard let result = result as? [String : AnyObject] else {
                finish(result: nil, error: NSError(domain: "Data error", code: -1011, userInfo: nil))
                return
            }
            
            //4.将结构回调
            finish(result: result["data"] as? [[String : AnyObject]], error: nil)
        }
        
        
    }
}


